package com.googlecode.agileplugins.cruisewatcher;

import com.intellij.ide.BrowserUtil;

import javax.swing.*;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.util.Random;

public final class BuildDialogPresenter {
    private static final Random RANDOM = new Random(System.currentTimeMillis());

    private CruiseBuild cruiseBuild;
    private CruiseWatcherSettings settings;
    private ImageDialog lastDialog;

    public BuildDialogPresenter(CruiseBuild cruiseBuild, CruiseWatcherSettings settings) {
        this.cruiseBuild = cruiseBuild;
        this.settings = settings;
    }

    void showImageDialog(boolean failed, String title, String buttonLabel) throws IOException {
        Icon imageIcon;
        String subFolder = failed ? cruiseBuild.getBrokenFolder() : cruiseBuild.getFixedFolder();
        File imageFolder = new File(new File(settings.baseImageFolder.trim()), subFolder.trim());
        File imageFile = getImageFile(imageFolder);
        File wavFile;
        if (imageFile != null) {
            imageIcon = new ImageIcon(imageFile.getCanonicalPath());
            wavFile = new File(imageFile.getCanonicalPath() + ".wav");
        } else {
            URL resource = getClass().getResource("build_" + (failed ? "broken" : "fixed") + ".jpg");
            imageIcon = new ImageIcon(resource);
            wavFile = null;
        }
        displayDialoag(failed, wavFile, imageIcon, title, buttonLabel);
    }

    private void displayDialoag(final boolean failed, final File wavFile, final Icon imageIcon, final String title, final String buttonLabel) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                boolean closed = closeExistingDialog();
                if (!closed || failed) {
                    Runnable clickAction = new Runnable() {
                        public void run() {
                            if (failed && cruiseBuild.getResultUrl() != null && cruiseBuild.getResultUrl().trim().length() > 0) {
                                String resultUrl = settings.baseUrl + cruiseBuild.getResultUrl();
                                BrowserUtil.launchBrowser(resultUrl);
                            }
                        }
                    };
                    final WavFilePlayer wavFilePlayer = new WavFilePlayer();
                    Runnable imageAction = new Runnable() {
                        public void run() {
                            wavFilePlayer.play(wavFile);
                        }
                    };
                    ImageDialog dialog = new ImageDialog(imageIcon, title, buttonLabel, clickAction, imageAction);
                    setDialog(dialog);
                    dialog.show();
                    wavFilePlayer.play(wavFile);
                }
            }
        });
    }

    private synchronized boolean closeExistingDialog() {
        if (lastDialog != null) {
            if (lastDialog.isShowing()) {
                lastDialog.close(-1);
                return true;
            }
            lastDialog = null;
        }
        return false;
    }

    private synchronized void setDialog(ImageDialog dialog) {
        lastDialog = dialog;
    }

    private File getImageFile(File imageFolder) {
        if (imageFolder == null || !imageFolder.exists()) {
            return null;
        }
        File[] children = imageFolder.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return file.isFile() && file.getName().matches(".*\\.(jpg|png|gif)");
            }
        });
        if (children == null || children.length == 0) {
            return null;
        }
        int index = RANDOM.nextInt(children.length);
        return children[index];
    }
}
